package com.xj.demo.classload;

import java.io.*;

public class UserClassLoader extends ClassLoader{
    private String classPath;
    public UserClassLoader(String classPath){
        this.classPath = classPath;
    }
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] classData = getClassData(name);
        if (classData == null) {
            throw new ClassNotFoundException();
        }
        return defineClass(name, classData, 0, classData.length);
    }

    private byte[] getClassData(String className){
        String path = classNameToPath(className);
        try {
            InputStream ins = new FileInputStream(path);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = ins.read(buffer)) != -1){
                baos.write(buffer, 0, len);
            }
            return baos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private String classNameToPath(String className){
        return classPath + "\\" + className.replace(".", "\\") + ".class";
    }

    public static void main(String[] args) throws ClassNotFoundException {
        UserClassLoader userLoader_1 = new UserClassLoader("H:\\gitee\\jvm-demo\\src\\main\\java");
        UserClassLoader userLoader_2 = new UserClassLoader("H:\\gitee\\jvm-demo\\src\\main\\java");
        Class<?> clazz_1 = userLoader_1.findClass("com.xj.demo.classload.User");
        Class<?> clazz_2 = userLoader_2.findClass("com.xj.demo.classload.User");
        System.out.println(clazz_1 == clazz_2);
    }
}
